import { ISpan, IAppCodeList } from "@ibiz/model-core";
import {
  CodeListEditorController,
  OpenAppViewCommand,
} from "@ibiz-template/runtime";
import { RuntimeModelError } from "@ibiz-template/core";

/**
 * 标签编辑器控制器
 *
 * @export
 * @class SpanEditorController
 * @extends {CodeListEditorController<ISpan>}
 */
export class SpanEditorController extends CodeListEditorController<ISpan> {
  /**
   * 值项
   *
   * @memberof SpanEditorController
   */
  public valueItem = "";

  /**
   * 代码表
   *
   * @type {(IAppCodeList | undefined)}
   * @memberof SpanEditorController
   */
  public codeList: IAppCodeList | undefined = undefined;

  /**
   * 初始化
   *
   * @protected
   * @return {*}  {Promise<void>}
   * @memberof SpanEditorController
   */
  protected async onInit(): Promise<void> {
    super.onInit();
    // span-link临时用editorItems
    if (this.model?.editorItems?.[0]) {
      this.valueItem = this.model.editorItems[0].id!;
    }
    // 初始化代码表
    if (this.model.appCodeListId) {
      const app = await ibiz.hub.getApp(this.context.srfappid);
      this.codeList = app.codeList.getCodeList(this.model.appCodeListId);
    }
  }

  /**
   * 打开数据链接视图
   *
   * @param {IData} data
   * @return {*}  {(Promise<IData[] | undefined>)}
   * @memberof SpanEditorController
   */
  public async openLinkView(data: IData): Promise<IData[] | undefined> {
    const { context, params } = this.handlePublicParams(
      data,
      this.context,
      this.params
    );
    if (data[this.valueItem]) {
      context.srfkey = data[this.valueItem];
    }
    const { linkAppViewId } = this.model;
    if (!linkAppViewId) {
      throw new RuntimeModelError(
        this.model,
        ibiz.i18n.t("editor.common.linkViewConfigErr")
      );
    }
    return ibiz.commands.execute(
      OpenAppViewCommand.TAG,
      linkAppViewId,
      context,
      params
    );
  }
}
